const alert1 = document.getElementById('alert1')
const alert2 = document.getElementById('alert2')
const canvas1 = document.getElementById('canvas1')
const ctx = canvas1.getContext('2d')
const keys = getStorageKeys()
const key = keys.length == 0 ? 1 : keys.at(-1) + 1
const color = ['red', 'blue', 'green'][key % 3]

function draw() {
  const { clientWidth, clientHeight } = document.body // body宽高
  const { screenX, screenY } = window // 屏幕坐标
  const barHeight = window.outerHeight - window.innerHeight // 浏览器顶部地址栏高度

  alert1.textContent = JSON.stringify({ clientWidth, clientHeight, screenX, screenY, barHeight }, '', 2)

  // canvas铺满body
  canvas1.width = clientWidth
  canvas1.height = clientHeight

  // 圆心坐标
  const x = clientWidth / 2
  const y = clientHeight / 2

  // 画圆
  ctx.fillStyle = color
  ctx.beginPath()
  ctx.arc(x, y, 15, 0, Math.PI * 2)
  ctx.fill()

  const position = {
    top: y + barHeight + screenY,
    left: x + screenX,
    color: color
  }

  

  getStorageKeys().forEach(k => {
    // if(k == key) return
    // console.log(k)
    const position2 = JSON.parse(localStorage.getItem(k))
    // console.log(position2)
    const w = position2.left - position.left // 横向间距
    const h = position2.top - position.top // 纵向间距
    // console.log(w, h)

    // 在自己的canvas上画出该圆
    ctx.fillStyle = position2.color;
    ctx.beginPath();
    ctx.arc(x + w, y + h, 15, 0, Math.PI * 2);
    ctx.fill();

    
  })

  for(k1 of getStorageKeys()){
    for(k2 of getStorageKeys()){
      // console.log(k1, k2)
      if(k1 == k2) continue
      const position1 = JSON.parse(localStorage.getItem(k1))
      const position2 = JSON.parse(localStorage.getItem(k2))

      const x1 = x + position1.left - position.left
      const y1 = y + position1.top - position.top
      const x2 = x + position2.left - position.left
      const y2 = y + position2.top - position.top

      // 画连接线
      ctx.strokeStyle = 'black'
      ctx.beginPath()
      ctx.moveTo(x1, y1)
      ctx.lineTo(x2, y2)
      ctx.stroke()
    }
  }


  localStorage.setItem(key, JSON.stringify(position))

  alert2.textContent = JSON.stringify(localStorage, '', 2)

  window.requestAnimationFrame(draw)
}

window.onunload = function() {
  localStorage.removeItem(key)
}

function getStorageKeys() {
  const keys = []
  for(let i = 0; i < localStorage.length; i++) {
    const k = Number(localStorage.key(i))
    !isNaN(k) && keys.push(k)
  }
  return keys.sort((a, b) => a - b)
}



window.requestAnimationFrame(draw)